package info.motteke.mixivoice4j.http;

import java.io.IOException;
import net.arnx.jsonic.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

public class JsonResponseHandler<T> implements ResponseHandler<T> {

    private static final Log logger = LogFactory.getLog(JsonResponseHandler.class);

    private final Class<T> clazz;

    public JsonResponseHandler(Class<T> clazz){
        this.clazz = clazz;
    }

    @Override
    public T handleResponse(HttpResponse res) throws ClientProtocolException, IOException {
        String html = EntityUtils.toString(res.getEntity(), "UTF-8");

        if(logger.isDebugEnabled()){
            logger.debug(clazz.getSimpleName() + " : " + html.replaceAll("\n", ""));
        }
        return JSON.decode(html, clazz);
    }
}
